package com.conlin.learn.common.proxy;

import com.conlin.learn.common.annotation.LogExecutionTime;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodLogger {

    public static void logExecutionTime(Object obj) throws IllegalAccessException, InvocationTargetException {
        for (Method method : obj.getClass().getDeclaredMethods()) {
            if (method.isAnnotationPresent(LogExecutionTime.class)) {
                // 获取方法参数
                Object[] args = new Object[method.getParameterCount()];
                // 调用方法并记录执行时间
                logMethodExecutionTime(method, obj, args);
            }
        }
    }

    private static void logMethodExecutionTime(Method method, Object obj, Object[] args) throws IllegalAccessException, InvocationTargetException {
        // 记录方法开始时间
        long startTime = System.currentTimeMillis();
        System.out.println("方法 " + method.getName() + " 开始执行...");

        // 调用目标方法
        Object result = method.invoke(obj, args);

        // 记录方法结束时间
        long endTime = System.currentTimeMillis();
        System.out.println("方法 " + method.getName() + " 执行完毕，耗时: " + (endTime - startTime) + " 毫秒");

        // 返回结果
        System.out.println("方法返回值: " + result);
    }
}